{% extends "templates/main_template.html.j2" %}

{% import "macros/select_options.html.j2" as SELECT_OPTIONS %}
{% import "macros/markdown_textarea.html.j2" as MARKDOWN_TEXTAREA %}
{% import "macros/tab_switcher.html.j2" as TAB_SWITCHER %}
{% import "macros/diff_table.html.j2" as DIFF_TABLE %}
{% import "macros/user_name.html.j2" as USER_NAME %}


{% block title -%}
  {{ USER_NAME.VALUE(target_user) }} · Сообщения · Farado
{%- endblock %}

{% set sent_messages = project_manager.messages_by_sender(
    user_id=target_user.id
  )
%}
{% set unread_sent_messages = project_manager.unread_messages_by_sender(
    user_id=target_user.id
  )
%}
{% set received_messages = project_manager.messages_by_receiver(
    user_id=target_user.id
  )
%}
{% set unread_received_messages = project_manager.unread_messages_by_receiver(
    user_id=target_user.id
  )
%}

{% set active_menu = 'users' %}

{% set tab_menu = [
  ['Входящие ['
    + unread_received_messages|length|string + '/'
    + received_messages|length|string + ']', 'inbox'],
  ['Исходящие ['
    + unread_sent_messages|length|string + '/'
    + sent_messages|length|string + ']', 'outgoing'],
  ['Написать сообщение', 'send_new'],
] %}


{#----------------------------------------------------------------------------#}
{% block styles %}
  <link href="/static/css/page-toolbar.css" rel="stylesheet" type="text/css" />
  {{ SELECT_OPTIONS.STYLES() }}
  {{ MARKDOWN_TEXTAREA.STYLES() }}
{% endblock %}


{#----------------------------------------------------------------------------#}
{% block breadcrumb %}
  <ol class="breadcrumb">
    <li class="breadcrumb-item active" aria-current="page">
      Сообщения пользователя:
      {{ USER_NAME.VALUE(target_user) }}
    </li>
  </ol>
{% endblock %}


{#----------------------------------------------------------------------------#}
{# Таб 1 — Входящие #}
{% block tab_content_1 %}
  <div class="row mt-3">
    <div class="col-12">
      <div class="accordion" id="accordion_messages">
        {% for message in received_messages %}
          {% set sender = project_manager.user(message.sender_id) %}
          <div class="accordion-item">
            {# Заголовок сообщения #}
              <h2 class="accordion-header"
                  id="panels_message_heading_{{ message.id }}">
                <button
                    class="accordion-button collapsed"
                    type="button"
                    data-bs-toggle="collapse"
                    data-bs-target="#panels_message_content_{{ message.id }}"
                    aria-expanded="true"
                    aria-controls="panels_message_content_{{ message.id }}"
                    onclick="read_message('{{ message.id }}');">
                  <div class="col-8">
                    <div id="was_read_message_caption_{{ message.id }}"
                        class="{% if not message.was_read %}collapse{% endif %}">
                      <i class="bi bi-envelope-open"></i>
                      {{ message.caption|e }}
                    </div>

                    <div id="not_read_message_caption_{{ message.id }}"
                        class="{% if message.was_read %}collapse{% endif %}">
                      <i class="bi bi-envelope"></i>
                      <strong>{{ message.caption|e }}</strong>
                    </div>
                  </div>

                  <div class="col me-3 text-end" style="white-space: nowrap;">
                    <small>
                      {# Оправитель #}
                        {% if sender %}
                          {{ USER_NAME.VALUE_WITH_ICON(sender) }}
                        {% endif %}
                      {# /Оправитель #}

                      {# Дата и время создания сообщения #}
                        <i class="bi bi-calendar-date"></i>
                        {{ message.formated_date_time() }}
                      {# /Дата и время создания сообщения #}
                    </small>
                  </div>
                </button>
              </h2>
            {# /Заголовок сообщения #}

            {# Контент сообщения #}
              <div id="panels_message_content_{{ message.id }}"
                  class="accordion-collapse collapse"
                  aria-labelledby="panels_message_heading_{{ message.id }}">
                <div class="accordion-body">
                  <p id="received_message_{{ message.id }}_markdown_result"></p>
                  <textarea
                      style="display:none;"
                      id="received_message_{{ message.id }}_markdown">
                    {{- project_manager.safe_value(message.content) -}}
                  </textarea>
                  <script>
                    document_ready_functions.push(function() {
                      markdownToHtml(
                        'received_message_{{ message.id }}_markdown',
                        'received_message_{{ message.id }}_markdown_result');
                    });
                  </script>
                  {# Таблица изменений запроса #}
                    {% set issue_change = project_manager.issue_change(message.issue_change_id) %}
                    {% if issue_change %}
                      {{ DIFF_TABLE.TAG(
                          issue_change,
                          project_manager)
                      }}
                    {% endif %}
                  {# /Таблица изменений запроса #}
                </div>
              </div>
            {# /Контент сообщения #}

          </div>
        {% endfor %}
      </div>
    </div>
  </div>
{% endblock tab_content_1 %}


{#----------------------------------------------------------------------------#}
{# Таб 2 — Исходящие #}
{% block tab_content_2 %}
  <div class="row mt-3">
    <div class="col-12">
      <div class="accordion" id="accordion_messages">
        {% for message in sent_messages %}
          {% set receiver = project_manager.user(message.receiver_id) %}
          <div class="accordion-item">
            {# Заголовок сообщения #}
              <h2 class="accordion-header"
                  id="panels_message_heading_{{ message.id }}">
                <button
                    class="accordion-button collapsed"
                    type="button"
                    data-bs-toggle="collapse"
                    data-bs-target="#panels_message_content_{{ message.id }}"
                    aria-expanded="true"
                    aria-controls="panels_message_content_{{ message.id }}">
                  <div class="col-8">
                    {% if message.was_read %}
                      <i class="bi bi-envelope-open"></i>
                      {{ message.caption|e }}
                    {% else %}
                      <i class="bi bi-envelope"></i>
                      <strong>{{ message.caption|e }}</strong>
                    {% endif %}
                  </div>

                  <div class="col me-3 text-end" style="white-space: nowrap;">
                    <small>
                      {# Получатель #}
                        {% if receiver %}
                          {{ USER_NAME.VALUE_WITH_ICON(receiver) }}
                        {% endif %}
                      {# /Получатель #}

                      {# Дата и время создания сообщения #}
                        <i class="bi bi-calendar-date"></i>
                        {{ message.formated_date_time() }}
                      {# /Дата и время создания сообщения #}
                    </small>
                  </div>
                </button>
              </h2>
            {# /Заголовок сообщения #}

            {# Контент сообщения #}
              <div id="panels_message_content_{{ message.id }}"
                  class="accordion-collapse collapse"
                  aria-labelledby="panels_message_heading_{{ message.id }}">
                <div class="accordion-body">
                  <p id="sent_message_{{ message.id }}_markdown_result"></p>
                  <textarea
                      style="display:none;"
                      id="sent_message_{{ message.id }}_markdown">
                    {{- project_manager.safe_value(message.content) -}}
                  </textarea>
                  <script>
                    document_ready_functions.push(function() {
                      markdownToHtml(
                        'sent_message_{{ message.id }}_markdown',
                        'sent_message_{{ message.id }}_markdown_result');
                    });
                  </script>
                  {# Таблица изменений запроса #}
                    {% set issue_change = project_manager.issue_change(message.issue_change_id) %}
                    {% if issue_change %}
                      {{ DIFF_TABLE.TAG(
                          issue_change,
                          project_manager)
                      }}
                    {% endif %}
                  {# /Таблица изменений запроса #}
                </div>
              </div>
            {# /Контент сообщения #}

          </div>
        {% endfor %}
      </div>
    </div>
  </div>
{% endblock tab_content_2 %}


{#----------------------------------------------------------------------------#}
{# Таб 3 — Написать сообщение #}
{% block tab_content_3 %}
  <div class="row mt-3">
    <div class="col-12">
      <form
          class="row g-3"
          action="/users/send_message/{{ target_user.id }}"
          method="post">
        {# -- Заголовок -- #}
          <div class="col-md-6">
            <label for="issue_project_id" class="form-label">Заголовок</label>
            <input
                type="text"
                name="message_caption"
                class="form-control"
                id="message_caption"
                required>
          </div>
        {# -- /Заголовок -- #}

        {# -- Получатели -- #}
          <div class="col-md-6">
            <label for="issue_version_id" class="form-label">Кому</label>
            {{ SELECT_OPTIONS.INPUT_MULTY(
                data_source = 'users',
                name = 'message_receivers',
                project_manager = project_manager,
                data_source_id = user.id)
            }}
          </div>
        {# -- /Получатели -- #}

        {# -- Сообщение -- #}
          <div class="col-12">
            <label for="message_content_tab" class="form-label">Сообщение</label>
            {{ MARKDOWN_TEXTAREA.INPUT(
                  'message_content_tab',
                  'message_content_result',
                  'message_content' ) }}
            <script>
              document_ready_functions.push(function() {
                {{ TAB_SWITCHER.DOCUMENT_READY_SCRIPT('message_content_tab') }}
              });
            </script>
          </div>
        {# -- /Сообщение -- #}

        {# -- Кнопка: Отправить -- #}
          <div class="col-12">
            <button
                type="submit"
                id="saveButton"
                class="btn btn-success float-end">
              <i class="bi bi-send"></i> Отправить
            </button>
          </div>
        {# -- /Кнопка: Отправить -- #}
      </form>
    </div>
  </div>
{% endblock tab_content_3 %}


{#----------------------------------------------------------------------------#}
{% block scripts %}
  {{ MARKDOWN_TEXTAREA.SCRIPTS() }}
  {{ SELECT_OPTIONS.SCRIPTS() }}
  <script>
    /* {# Переменные для изменения общего кол-ва непрочитанных сообщений #} */
    var unread_received_messages_count = {{ unread_received_messages|length }}
    var received_messages_count = {{ received_messages|length|string }}

    function read_message(message_id) {
      $.ajax({
        type: 'POST',
        url: '/users/read_message/{{ target_user.id }}/' + message_id,
        success: function(msg) {
          if (msg != "was_read") {
            return;
          }
          unread_received_messages_count--;
          $("#inbox-tab .title-tab").html(
            "Входящие ["
            + unread_received_messages_count + "/"
            + received_messages_count + "]"
          );
        }
      });

      $("#not_read_message_caption_" + message_id).attr("class", "collapse");
      $("#was_read_message_caption_" + message_id).attr("class", "");
    }
  </script>
{% endblock %}
